import Taro from '@tarojs/taro'
import React, { useEffect, useState, useCallback } from 'react'
import {
  View, Text, Image, Button
} from '@tarojs/components'
import { useSelector, useDispatch } from 'react-redux'
import { validation, dataFetch } from '@pier88health/p8h-common'
import authActions from '@ACTIONS/auth'
import i18n from '@I18N'
import Images from '@ASSET/Images'
import PhoneInput from '@COMPONENTS/CustomInput/PhoneInput'
import AuthCodeInput from '@COMPONENTS/CustomInput/AuthCodeInput'
import Navigate from '@NAVIGATION/navigateManager'
import './LoginModal.scss'

export default function LoginModal({ showModal, onCloseModal, onLoginSuccess }) {
  const { formatPhoneNumber } = dataFetch
  const [show, setShow] = useState(false)
  const [phone, setPhone] = useState('')
  const [showPhone, setShowPhone] = useState('')
  const [canShowPhone, setCanShowPhone] = useState(false)
  const [code, setCode] = useState('')
  const [agree, setAgree] = useState(false)
  const dispatch = useDispatch()
  const { dispatchRequestAuthCode, dispatchLoginOrRegisterByPhone, dispatchSetLoginSuccessInfo } = authActions
  const actionTokenId = useSelector(state => state.auth.ActionTokenId)

  useEffect(() => {
    if (showModal !== show) {
      setShow(showModal)
    }
  }, [showModal, show])

  const requestAuthCode = useCallback(params => dispatch(dispatchRequestAuthCode(params)), [dispatch, dispatchRequestAuthCode])
  const setLoginSuccessInfo = useCallback(params => dispatch(dispatchSetLoginSuccessInfo(params)), [dispatch, dispatchSetLoginSuccessInfo])
  const loginSubmit = useCallback(
    (payload, webCallback) => dispatch(dispatchLoginOrRegisterByPhone({ payload, webCallback })), [dispatch, dispatchLoginOrRegisterByPhone]
  )

  const onClose = useCallback(() => {
    setShow(false)
    onCloseModal()
  }, [onCloseModal])

  const onCloseBtn = useCallback(() => {
    onClose()
    setLoginSuccessInfo()
  }, [onClose, setLoginSuccessInfo])

  const onInputPhone = useCallback(e => {
    const { value } = e.detail
    setPhone(value)
  }, [])

  const onClearPhone = useCallback(() => {
    setPhone('')
    setShowPhone('')
  }, [])

  const onBlur = useCallback(() => {
    const value = formatPhoneNumber(phone)
    setShowPhone(value)
    setCanShowPhone(true)
  }, [phone, formatPhoneNumber])

  const onFocus = useCallback(() => {
    setCanShowPhone(false)
  }, [])

  const onInputCode = useCallback(e => {
    const { value } = e.detail
    setCode(value.replace(/\s/g, ''))
  }, [])

  const getAuthCode = () => {
    const payload = { PhoneNumber: phone }
    requestAuthCode(payload)
  }

  const getSubmitStatus = useCallback(() => {
    const isValidPhoneNumber = validation.isPhoneNumber(phone)
    const isValidAuthCode = code.length === 4
    return isValidPhoneNumber && isValidAuthCode && agree
  }, [phone, code, agree])

  const agreePolicy = useCallback(() => {
    setAgree(!agree)
  }, [agree])
  const onClickPolicy = e => {
    e?.stopPropagation?.()
    Navigate.policy()
  }
  const onClickAgreement = e => {
    e?.stopPropagation?.()
    Navigate.agreement()
  }
  const onLoginSuccessCallback = useCallback(() => {
    onClose()
    onLoginSuccess?.()
  }, [onClose, onLoginSuccess])

  const onSubmit = () => {
    const payload = {
      PhoneNumber: phone,
      ActionTokenId: actionTokenId,
      AuthCode: code,
      AcquireChannel: Taro.getEnv()
    }
    loginSubmit(payload, onLoginSuccessCallback)
  }

  const canLogin = getSubmitStatus()
  return (
    <View className={`login-modal-container ${show ? 'show' : ''}`}>
      <View className="modal">
        <View className="modal-header">
          <View className="login-title-container">
            <Text className="login-title">{i18n.login.login()}</Text>
          </View>
          <View className="login-desc-container">
            <Text className="phone_tips">{i18n.login.phone_tips()}</Text>
          </View>
        </View>
        <View className="login-form">
          <PhoneInput
            phone={phone}
            showPhone={showPhone}
            onInput={onInputPhone}
            onClear={onClearPhone}
            show={canShowPhone}
            onBlur={onBlur}
            onFocus={onFocus}
            placeholder={i18n.login.placeholder_phone()}
          />
          <AuthCodeInput
            code={code}
            phone={phone}
            onInput={onInputCode}
            getAuthCode={getAuthCode}
            placeholder={i18n.login.placeholder_code()}
          />
          <Button
            formType="submit"
            disabled={!canLogin}
            className="login-btn"
            onClick={canLogin && onSubmit}
          >
            {i18n.button.login()}
          </Button>
          <View className="agree-container" onClick={agreePolicy}>
            <Image src={agree ? Images.login.selected : Images.login.unselect} className="agree-icon" />
            <Text className="agree-text">
              我已同意
              <Text className="agree-link" onClick={onClickAgreement}>疼爱健康用户协议</Text>
              <Text>及</Text>
              <Text className="agree-link" onClick={onClickPolicy}>隐私政策</Text>
            </Text>
          </View>
        </View>
        <View className="close-btn" onClick={onCloseBtn}>
          <Image src={Images.login.close_modal} className="close-btn-img" />
        </View>
      </View>
    </View>
  )
}
